package socket.bio;

import javax.net.ServerSocketFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @description: 类描述
 * @author: Fesine
 * @createTime:2016/9/29 14:47
 * @update:修改内容
 * @author: Fesine
 * @updateTime:2016/9/29 14:47
 */
public class BIOSocket {
    public static void main(String[] args) {
        ServerSocket ss = null;
        Socket socket = null;
        try {
            ss = ServerSocketFactory.getDefault().createServerSocket(8383);
            System.out.println("--- Server is started");
            while (true) {
                try {
                    //监听直到授受连接后返回一个新socket对象
                    socket = ss.accept();//阻塞
                    //new 一个线程处理连接请求
                    new Thread(new BIOSocket().new BIOWorker(socket)).start();
                } catch (Throwable e) {
                    e.printStackTrace();
                }

            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private static String getAnswer(String question) {
        String answer = null;
        switch (question) {
            case "who":
                answer = "my name is fesine";
                break;
            case "what":
                answer = "do IT!";
                break;
            case "where":
                answer = "from jiangsu wuxi";
                break;
            default:
                answer = "请输入who,what,where";
        }
        return answer;
    }

    private class BIOWorker implements Runnable {

        private Socket socket;

        public BIOWorker(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            BufferedReader br = null;
            PrintWriter pw = null;

            try {
                br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                pw = new PrintWriter(socket.getOutputStream());
                String question = br.readLine();//没有内容会阻塞
                System.out.println("request from client:"+ question);
                while (!question.equals("over")) {
                    String answer = getAnswer(question);
                    pw.println(answer);
                    question = br.readLine();
                }
                pw.println("over!");
                pw.flush();
                if (pw != null) {
                    pw.close();
                }
                if (br != null) {
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
